<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="this.query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="部门名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="serch">查询</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>

			</el-form>
		</el-col>

		<!--列表-->
		<template>
			<el-table :data="pageInfo.rows"
                highlight-current-row
                v-loading="loading"
                @selection-change="handleSelectionChange"
                style="width: 100%;">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>

				<el-table-column prop="name" label="部门" width="120" sortable>
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间" width="200"  sortable>
				</el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="200"  sortable>
        </el-table-column>
        <el-table-column prop="manager.username" label="负责人" width="200"  sortable>
        </el-table-column>
        <el-table-column prop="parent.name" label="父部门" width="200" sortable>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="100" sortable>
        </el-table-column>
				<el-table-column prop="state" label="状态" width="100" sortable>
          <template slot-scope="scope">
            <span style="color: #11b95c" v-if="scope.row.state == 1">启用</span>
            <span style="color: red" v-else>禁用</span>
          </template>
				</el-table-column>

				<el-table-column prop="intro" label="介绍" min-width="180" sortable>
				</el-table-column>
        <el-table-column label="操作" width="150">
          <template scope="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
			</el-table>
		</template>
    <!--分页工具条-->
    <!--
       @size-change="handleSizeChange" 当每页条数变化的时候触发
        @current-change="handleCurrentChange" 当前页码数据变化触发
        :current-page="currentPage4" 当前页数
        :page-size="100" : 每页条数
        :page-sizes="[5, 10, 20, 40]"
         :total="this.pageInfo.total" 总条数
    -->
    <!--工具条-->
    <el-col :span="24" class="toolbar">
    <el-button type="danger" v-on:click="batchDelete">批量删除</el-button>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.query.currentPage"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="this.query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        style="float:right;"
        :total="this.pageInfo.total">
    </el-pagination>
    </el-col>
    <!--
      新增界面 用于新增部门 和 修改部门
      v-model="addFormVisible": 这个属性是用于控制 对话框是否显示的 true就显示 false 就不显示
      弹出框和其他的不一样  我们现在的版本v-model 不合适   换成:visible.sync
      :rules="addFormRules" 这是一个验证规则
      prop="name" 是name 表示规则中匹配的是name
    -->
    <el-dialog title="新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="负责人" >
          <!--<el-input v-model="saveForm.manager.id" auto-complete="off"></el-input>-->
          <el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父部门" >
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="路径" >
          <el-input v-model="saveForm.path" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="启用禁用">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="部门简介">
          <el-input type="textarea" v-model="saveForm.intro"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>
<script>
	import { getUserList } from '../../api/api';
	//import NProgress from 'nprogress'
	export default {
		data() {
			return {

				loading: false,
        pageInfo:{
				  total:0,
          rows:[]
        },
        query:{
				  currentPage:1,
          pageSize:10,
          keyword:''
        },
        selColu:[],
        // 修改和新增相关数据
        saveFormVisible:false, //新增/修改弹出框隐藏
        addFormRules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' } // trigger触发 blur 失焦
          ]

        },
        employees:[],
        saveForm:{
				  name:"",
          manager:{
				    id:null,
            username:""
          },
          parent:{
				    name:"",
            id:null
          },
          intro:"",
          state: ""
        },
        addLoading : false,
        deptTree:[] // 定义部门树
			}

		},
		methods: {
		  // 查询部门树
      getParents(){
        this.$http.get("/department/deptTree")
            .then(result=>{
              result = result.data
              if (result.success){
                console.log(result.objData)
                this.deptTree = result.objData;
              }else{
                this.$message({message: '请联系管理员!',type: 'warning' });
              }
            }).catch(result=>{
          this.$message({message: '糟糕网络异常,请稍后再试!',type: 'warning' });
        })
      },
		  // 查询管理数据
      getEmployees(){
        this.$http.get("/employee")
            .then(result=>{
              result = result.data
              if (result.success){
               this.employees = result.objData;
              }else{
                this.$message({message: '请联系管理员!',type: 'warning' });
              }
            }).catch(result=>{
          this.$message({message: '糟糕网络异常,请稍后再试!',type: 'warning' });
        })
      },
		  // 点击编辑的方法
      handleEdit(index,row){
        /**
         * path 是用来标记 父部门们的
         */
        // 显示弹框
        this.saveFormVisible = true;
        let temp = Object.assign({}, row);
        console.log("row",row);
        console.log("saveForm",temp);
        if(!temp.parent){
          temp.parent={
            id:null,
            name:""
          }
        }
        if(!temp.manager){
          temp.manager={
            id:null,
            username:""
          }
        }

        this.getEmployees()
        this.getParents()
        var path = temp.path.split("/")
        // path ""/1/2/3
        var pathurl = []
        for (let i = 1; i < path.length-1; i++) {
          pathurl.push(parseInt(path[i]))  // 获取到的是字符串 需要转换为数字
        }
        temp.parent = pathurl
        // 回显数据
        this.saveForm = temp;
      },
		  // 点击保存数据
      saveSubmit(){
        var saveForm = this.saveForm;
        var parent = saveForm.parent;
        if(parent){
          // 处理path
          var join = "/"+parent.join("/");
          saveForm.path = join;
          console.log(join)
          // 如果选择父部门 就取到最后一个id 为 父部门的id
          let pid = parent[parent.length - 1]
          saveForm.parent = {
            id : pid,
            name:""
          }
          console.log(this.saveForm)
        }


        this.$http.post("/department",saveForm)
        .then(result=>{
          result = result.data
          if (result.success){
              // 关弹框
            this.saveFormVisible = false;
            // 回到第一页
            this.query.currentPage = 1
             //刷新页面
            this.getDepartments()
          }else{
            this.$message({message: '请联系管理员!',type: 'warning' });
          }
        }).catch(result=>{
          this.$message({message: '糟糕网络异常,请稍后再试!',type: 'warning' });
        })
      },

		  // 点击新增按钮
      handleAdd(){

        this.saveForm={
          name:"",
            manager:{
            id:null,
            username:""
          },
          parent:{
            name:"",
            id:null
          },
          intro:"",
          state: ""
        }
        this.getEmployees()
        this.getParents()
        this.saveFormVisible = true;
      },
		  // 批量删除 val所有被选中的行数据 但是都是 对象
      batchDelete(){
        var ids = this.selColu.map(x=>x.id);
        if (ids.length == 0 ){
          this.$message({message: '请选择要删除的部门',type: 'warning' });
          return ;
        }
        this.$http.patch("/department",ids)
            .then(result=>{
              result = result.data
              if (result.success){
                this.$message({message: '删除成功',type: 'success' });
                // 将当前页 设置为 第一页
                this.query.currentPage = 1
                this.getDepartments();
              }else {
                this.$message({message: '请联系管理员!',type: 'warning' });
              }
            }).catch(result=>{
          this.$message({message: '糟糕网络异常,请稍后再试!',type: 'warning' });
        })
      },
      handleSelectionChange(val){
        this.selColu = val;
      },

      // 删除指定
      handleDel(index,row){
        var id = row.id;
        // 发送axios请求
        this.$http.delete("/department/"+id)
        .then(result=>{
          result = result.data
          if (result.success){
            this.$message({message: '删除成功',type: 'success' });
            // 将当前页 设置为 第一页
            this.query.currentPage = 1
            this.getDepartments();
          }else {
            this.$message({message: '请联系管理员!',type: 'warning' });
          }
        }).catch(result=>{
          this.$message({message: '糟糕网络异常,请稍后再试!',type: 'warning' });
        })
      },
      serch(){
        this.query.currentPage = 1;
        this.getDepartments();
      },
			//handleSizeChange更改每页条数的时候
      handleSizeChange(val){
       this.query.pageSize = val;
       this.query.currentPage = 1;
       // 调用查询
        this.getDepartments();
      },
      //handleCurrentChange 页码变化触发
      handleCurrentChange(val){
        this.query.currentPage = val;
        // 调用查询
        this.getDepartments();
      },

			//获取部门列表分页
			getDepartments: function () {
				// 发送后台的请求 axios 每一个axios都请求 http:/localhost:8080
        this.$http.put("/department",this.query)
        .then(result=>{
          console.log(result);
          // {data: {…}, status: 200, statusText: 'OK', headers: {…}, config: {…}, …}
          result = result.data
          // data:{success: true, msg: '操作成功', objData: {…}}
          if (result.success){
            this.pageInfo = result.objData
           // this.departments = result.objData.rows;
          }else{
            // this.$message({message: '查询失败请联系管理员',type: 'warning' });
          }
        })
        .catch(result =>{
          // this.$message({message: '糟糕网络异常,请稍后再试!',type: 'warning' });
        })
        // then

        // catch
			}
		},
		mounted() {
			this.getDepartments();
		}
	};

</script>

<style scoped>

</style>